#include <mh/util.hpp>
#include <mh/audio/xaudio.hpp>

namespace Mh
{
	namespace Audio
	{
		::HMODULE	s_module;	// DLL 핸들

		// 이하 SystemXA 정의
		SystemXA::SystemXA()
			:	System( TYPE_XAUDIO2 ),	m_device( NULL ), m_master( NULL )
		{}

		SystemXA::~SystemXA()
		{
			this->finalize();
		}

		bool SystemXA::initialize()
		{
			HRESULT hr;

			// 라이브러리 링크
			{
				s_module = ::LoadLibrary( TEXT("Xaudio2.dll") );
				if( !s_module )
					return false;
			}

			// create device
			{
				::UINT32 flags = 0;
#ifdef	_MH_DEBUG_
				flags = XAUDIO2_DEBUG_ENGINE;
#endif	// _MH_DEBUG_
				::XAUDIO2_PROCESSOR processor = ::XAUDIO2_DEFAULT_PROCESSOR;
				hr = ::XAudio2Create( &m_device, flags, processor );
				if( FAILED(hr) )
					return false;
			}

			if( !this->create_voices() )
				return false;

			return true;
		}

		void SystemXA::finalize()
		{
			if( m_master )
			{
				m_master->DestroyVoice();
				m_master = NULL;
			}
			SafeRelease( &m_device );

			if( !s_module )
			{
				::FreeLibrary( s_module );
				s_module = NULL;
			}
		}

		void SystemXA::suspend()
		{
		}

		void SystemXA::process()
		{
		}

		bool SystemXA::create_voices( ::UINT32 device )
		{
			HRESULT hr;

			// create master voice
			hr = m_device->CreateMasteringVoice( &m_master, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, device, NULL );
			if( FAILED(hr) )
				return false;

			// create submix voices

			return true;
		}

	}		// namespace Mh
}			// namespace Mh::Audio